-- UIDungeonStatusBar
-- create by zouyb
-- 地牢中状态条菜单

local STATUS_ICON_WIDTH = 46;
local STATUS_ICON_GAP = 10;
local STATUS_ICON_LEFT_MARGIN = 30;

-- UIDungeonStatusBar
UIDungeonStatusBar = class("UIDungeonStatusBar", function()
    return {};
end);

function UIDungeonStatusBar.create()
    return UIDungeonStatusBar.new();
end

-- 构造函数
function UIDungeonStatusBar:ctor()
end

-- 更新状态条
function UIDungeonStatusBar:updateBar()

    -- 显示普通属性类
    -- self:updatePropBar();

    -- 显示状态赋予的属性类
    self:updateStatusBar();
end

function UIDungeonStatusBar:updateStatusBar()
    -- 获取当前所有的status
    local statusList = table.deepcopy(ME.user.dbase:query("combat_status", {}));
    local idList = table.keys(statusList);

    -- 获取当前的光环
    local assistList = table.add(ME.user.dbase:queryTemp("assist_map", {}), ME.user.dbase:queryTemp("assist_summon_map", {}));
    assistList = table.add(assistList, ME.user.dbase:queryTemp("assist_grid_map", {}));
    local assistIdList = table.keys(assistList);

    -- 上次显示的列表
    local lastStatusList = self.lastStatusList or {};
    local lastAssistList = self.lastAssistList or {};

    -- 两次都是空的
    if #lastStatusList <= 0 and #idList <= 0 and
        #lastAssistList <= 0 and #assistIdList <= 0 then
        return;
    end

    -- 待删除列表
    local deleteList = {};
    for _, status in pairs(lastStatusList) do
        if not statusList[status] then
            table.insert(deleteList, status);
        end
    end

    local deleteAssistList = {};
    for _, id in pairs(lastAssistList) do
        if not assistList[id] then
            table.insert(deleteAssistList, id);
        end
    end

    if #deleteList == 0 and #deleteAssistList == 0 then
        -- 没有需要删除的，直接显示
        self:showStatusBar(statusList, assistList);
    else
        -- 在需要删除的图标上播放消失动画
        for _, deleteId in pairs(deleteList) do
            local node = tolua.cast(self.propNodeList[deleteId], "cc.Node");
            if node then
                node.iconImg:setVisible(false);
                node.numLabel:setVisible(false);
                playEffect(node, 4028, 0, 0, nil, 0.5);
            end
        end

        for _, deleteId in pairs(deleteAssistList) do
            local assistKey = "assist" .. deleteId;
            local node = tolua.cast(self.propNodeList[assistKey], "cc.Node");
            if node then
                node.iconImg:setVisible(false);
                node.numLabel:setVisible(false);
                playEffect(node, 4028, 0, 0, nil, 0.5);
            end
        end

        -- 等待删除光效播放完毕，在重新显示
        local uiLevel = UIDungeonMgr.getCurLevel();
        if uiLevel ~= nil then
            performWithDelay(uiLevel, function() self:showStatusBar(statusList, assistList); end, 0.5);
        end
    end

    -- 更新上次的propID列表
    self.lastStatusList = idList;
    self.lastAssistList = assistIdList;
end

-- 显示状态条
function UIDungeonStatusBar:showStatusBar(statusList, assistList)
    local uiLevel = UIDungeonMgr.getCurLevel();
    if not uiLevel then
        return;
    end

    uiLevel.statusBarNode:stopAllActions();

    -- 计算各个分辨率下分别需要伸出去多少
    local delta = 0;

    -- 计算最左边的点的坐标
    local pos = uiLevel.statusBarNode:getParent():convertToNodeSpace(cc.p(0, 0));

    -- 计算状态条需要伸出去多少
    local statusNum = #table.keys(statusList) + #table.keys(assistList);
    local xDistance = STATUS_ICON_LEFT_MARGIN + (statusNum * (STATUS_ICON_WIDTH + STATUS_ICON_GAP) - STATUS_ICON_GAP);
    if statusNum == 0 then
        xDistance = uiLevel.statusBarInitPos.x - pos.x;
    end

    uiLevel.statusBarNode:runAction(cc.MoveTo:create(0.2, cc.p(pos.x + xDistance, uiLevel.statusBarInitPos.y)));

    -- 生成BUFF图标
    local parentNode = uiLevel.statusParentNode;
    parentNode:removeAllChildren();
    self.propNodeList = {};

    parentNode:setPositionX(uiLevel.statusParentInitPos.x);

    local pos = 0;
    local totalWidth = 0;
    for status, condition in pairs(statusList) do
        local node = cc.CSLoader:createNode("layout/dungeon/DungeonStatusItem.csb");
        local iconImg = findChildByName(node, "icon");
        local numLabel = findChildByName(node, "icon/num");
        local statusInfo = CombatStatusM.getStatusInfo(status);

        node.iconImg = iconImg;
        node.numLabel = numLabel;

        iconImg:loadTexture(getStatusIconPath(statusInfo["icon"]));

        iconImg.status = status;
        iconImg.round = condition["end_round"];
        iconImg.name = CombatStatusM.getStatusName(ME.user, status);
        iconImg.effect = CombatStatusM.getStatusDesc(ME.user, status, condition);

        if iconImg.round == NUMBER_INFINITY then
            -- 如果状态回合数不限，则隐藏回合倒计时
            numLabel:setVisible(false);
        else
            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BEIGE, true);
            numLabel:setString(tostring(iconImg.round - CombatM.getRound()));
            TextStyleM.setOutlineStyle(numLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
            numLabel:setVisible(true);
        end

        local function onImgClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_caption");
                local tipStr = "";
                local restRound = sender.round - CombatM.getRound();

                local effectDesc = sender.effect;
                if restRound > 0 then
                    tipStr = string.format(getLocStr("hero_attribute_buff_tip"), effectDesc, restRound);
                elseif CombatStatusM.query(sender.status, "save") == 1 then --神圣重生需要显示为本次迷宫起效
                    tipStr = string.format(getLocStr("hero_attribute_buff_tip2"), effectDesc);
                else
                    tipStr = string.format(getLocStr("hero_attribute_buff_tip1"), effectDesc);
                end

                local title = string.format(getLocStr("status_title"), sender.name);

                -- 显示通用说明界面
                showHint2(title, tipStr);
            end
        end
        iconImg:addTouchEventListener(onImgClick);

        node:setPositionX(totalWidth)

        parentNode:addChild(node);
        self.propNodeList[status] = node;

        totalWidth = totalWidth + (STATUS_ICON_WIDTH + STATUS_ICON_GAP);
    end

    for assistId, count in pairs(assistList) do
        local node = cc.CSLoader:createNode("layout/dungeon/DungeonStatusItem.csb");
        local iconImg = findChildByName(node, "icon");
        local numLabel = findChildByName(node, "icon/num");
        local assistInfo = AssistMonsterM.query(assistId);

        node.iconImg = iconImg;
        node.numLabel = numLabel;

        iconImg:loadTexture(getStatusIconPath(assistInfo["icon"]));

        local desc = AssistMonsterM.getAssistDesc(assistId, count);
        iconImg.name = assistInfo.name;
        iconImg.effect = desc;

        -- 光环不需要倒计时
        numLabel:setVisible(false);

        local function onImgClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_caption");

                -- 显示通用说明界面
                showHint2(sender.name, sender.effect);
            end
        end
        iconImg:addTouchEventListener(onImgClick);

        node:setPositionX(totalWidth)

        local assistKey = "assist" .. assistId;
        parentNode:addChild(node);
        self.propNodeList[assistKey] = node;

        totalWidth = totalWidth + (STATUS_ICON_WIDTH + STATUS_ICON_GAP);
    end

    -- 最后一个的gap要减回来
    totalWidth = totalWidth - STATUS_ICON_GAP;

    -- 右对齐
    parentNode:setPositionX(parentNode:getPositionX() - (totalWidth - STATUS_ICON_WIDTH));
end

-------------------------------------------------------------------------- 下面是旧的，暂时保留

-- function UIDungeonStatusBar:updatePropBar()
-- 	-- 获取当前所有的prop列表
-- 	local rawPropList = PropM.getBuff(ME.user);
--     rawPropList = table.append(rawPropList, PropM.getDebuff(ME.user));
--     rawPropList = table.append(rawPropList, PropM.getSpecialProp(ME.user));

--     -- 移除不显示的
--     local propList = {};
--     for _, prop in pairs(rawPropList)  do
--         if not FormulaM.invoke("IS_UNSHOWN_PROP", prop) then
--             table.insert(propList, prop);
--         end
--     end

-- 	-- 收集ID列表
-- 	local propIdList = {};
-- 	for _, prop in pairs(propList) do
-- 		table.insert(propIdList, prop[1]);
-- 	end

-- 	if self.lastPropIdList == nil then
-- 		-- 首次显示，直接全部显示出来
-- 		self:showBar(propList);

--         -- 更新上次的propID列表
--         self.lastPropIdList = propIdList;
-- 		return;
-- 	end

-- 	-- 待删除列表
-- 	local deleteList = {};

-- 	-- 和上次比较
-- 	if #propIdList == 0 and #self.lastPropIdList == 0 then
-- 		-- 上次空的，本次也是空的，直接返回
-- 		return;
-- 	end

-- 	-- 比较出需要删除的
-- 	for _, propId in pairs(self.lastPropIdList) do
-- 		if table.indexOf(propIdList, propId) == -1 then
-- 			table.insert(deleteList, propId);
-- 		end
-- 	end

-- 	if #deleteList == 0 then
-- 		-- 没有需要删除的，直接显示
-- 		self:showBar(propList);
-- 	else
-- 		-- 在需要删除的图标上播放消失动画
-- 		for _, deleteId in pairs(deleteList) do
-- 			local node = self.propNodeList[deleteId];
-- 			node.iconImg:setVisible(false);
-- 			node.numLabel:setVisible(false);
-- 			playEffect(node, 4028, 0, 0, nil, 0.5);
-- 		end

-- 		-- 等待删除光效播放完毕，在重新显示
-- 		local uiLevel = UIDungeonMgr.getCurLevel();
-- 		if uiLevel ~= nil then
-- 		    performWithDelay(uiLevel, function() self:showBar(propList); end, 0.5);
-- 		end
-- 	end

-- 	-- 更新上次的propID列表
-- 	self.lastPropIdList = propIdList;
-- end

-- -- 整理状态效果
-- function UIDungeonStatusBar:getStatusEffect(sender)
--     if sender.propId ~= 507 then
--         -- 不是诅咒状态，返回原值
--         return sender.effect;
--     else
--         -- 根据玩家的诅咒效果削减计算显示用的效果
--         local p = PropM.combine(ME.user, "curse_resist", 1);
--         local effect = PropM.combine(ME.user, "curse", 1);

--         -- 最多削减到0
--         p = math.max(1000 - p[3], 0);
--         return string.gsub(sender.effect, tostring(effect[3] / 10), tostring(math.modf(effect[3] * p / 1000 / 10)));
--     end
-- end

-- -- 显示状态条
-- function UIDungeonStatusBar:showBar(propList)
-- 	local uiLevel = UIDungeonMgr.getCurLevel();
-- 	uiLevel.statusBarNode:stopAllActions();

-- 	-- 计算各个分辨率下分别需要伸出去多少
-- 	local delta = 0;

--     -- 计算最左边的点的坐标
--     local pos = uiLevel.statusBarNode:getParent():convertToNodeSpace(cc.p(0, 0));

-- 	-- 计算状态条需要伸出去多少
-- 	local xDistance = STATUS_ICON_LEFT_MARGIN + (#propList * (STATUS_ICON_WIDTH + STATUS_ICON_GAP) - STATUS_ICON_GAP);
-- 	if #propList == 0 then
--         xDistance = uiLevel.statusBarInitPos.x - pos.x;
-- 	end

--     uiLevel.statusBarNode:runAction(cc.MoveTo:create(0.2, cc.p(pos.x + xDistance, uiLevel.statusBarInitPos.y)));

-- 	-- 生成BUFF图标
-- 	local parentNode = uiLevel.statusParentNode;
-- 	parentNode:removeAllChildren();
-- 	self.propNodeList = {};

-- 	parentNode:setPositionX(uiLevel.statusParentInitPos.x);

-- 	local pos = 0;
-- 	local totalWidth = 0;
-- 	for _, prop in pairs(propList) do
-- 		local node = cc.CSLoader:createNode("layout/dungeon/DungeonStatusItem.csb");
-- 		local iconImg = findChildByName(node, "icon");
-- 		local numLabel = findChildByName(node, "icon/num");
-- 		node.iconImg = iconImg;
-- 		node.numLabel = numLabel;

-- 		iconImg:loadTexture(getStatusIconPath(PropM.getPropIcon(prop)));
-- 		iconImg.propId = prop[1];
-- 		iconImg.round = prop[4];
--         print("iconImg.round:"..iconImg.round..",leftRound:"..iconImg.round - CombatM.getRound());
-- 		iconImg.targetRound = prop[4];
-- 		iconImg.name = "";
-- 		iconImg.effect = PropM.getPropDesc(prop);
-- 		if iconImg.round == NUMBER_INFINITY then
-- 			-- 如果状态回合数不限，则隐藏回合倒计时
-- 			numLabel:setVisible(false);
-- 		else
--             TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_TINY, TextStyleM.TEXT_COLOR_BEIGE, true);
-- 			numLabel:setString(tostring(iconImg.round - CombatM.getRound()));
-- 			TextStyleM.setOutlineStyle(numLabel, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
-- 			numLabel:setVisible(true);
-- 		end

-- 		local function onImgClick(sender, eventType)
-- 			if eventType == ccui.TouchEventType.ended then
-- 				AudioM.playFx("button_caption");
-- 				local tipStr = "";
-- 				local restRound = sender.round - CombatM.getRound();
--                 print("sender.round:"..sender.round..",restRound:"..restRound);
-- 				local effectDesc = self:getStatusEffect(sender);
-- 				if restRound > 0 then
-- 					tipStr = string.format(getLocStr("hero_attribute_buff_tip"), effectDesc, restRound);
-- 				elseif sender.propId == 5 then --神圣重生需要显示为本次迷宫起效
-- 					tipStr = string.format(getLocStr("hero_attribute_buff_tip2"), effectDesc);
-- 				else
-- 					tipStr = string.format(getLocStr("hero_attribute_buff_tip1"), effectDesc);
-- 				end

-- 				local propAlias = PropM.getPropAlias(sender.propId);
-- 				local title = string.format(getLocStr("status_title"), propAlias);

-- 				-- 显示通用说明界面
-- 				showHint2(title, tipStr);
-- 			end
-- 		end
-- 		iconImg:addTouchEventListener(onImgClick);

--         node:setPositionX(totalWidth)

-- 		parentNode:addChild(node);
--         self.propNodeList[prop[1]] = node;

-- 		totalWidth = totalWidth + (STATUS_ICON_WIDTH + STATUS_ICON_GAP);
-- 	end

--     -- 最后一个的gap要减回来
--     totalWidth = totalWidth - STATUS_ICON_GAP;

--     -- 右对齐
--     parentNode:setPositionX(parentNode:getPositionX() - (totalWidth - STATUS_ICON_WIDTH));
-- end


